package 英译汉;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

public class UdpEchoServer {
    DatagramSocket socket=null;
    HashMap<String,String>hashMap=new HashMap<>();
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
        hashMap.put("hello","你好");
        hashMap.put("cat","猫");
        hashMap.put("tedious","冗余的");
    }
    protected String precess(String s){
        if(hashMap.containsKey(s)){
            return hashMap.get(s);
        }
        String str="在表中不存在";
        return str;
    }
    public void start() throws IOException {
        while (true) {
            DatagramPacket request=new DatagramPacket(new byte[4096],4096);
            socket.receive(request);
            String receive=new String(request.getData(),0,request.getLength());
            String response=precess(receive);
            DatagramPacket datagramresponse=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    request.getSocketAddress());
            socket.send(datagramresponse);
            String log=String.format("[%s,%d],request:%s,response: %s",
                    request.getAddress().toString(),
                    request.getPort(),
                    receive,
                    response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
